<template>
  <el-card class="form-container" shadow="never">
    <el-form :model="coupon"
             :rules="rules"
             ref="couponFrom"
             label-width="150px"
             size="small">
      <el-form-item label="优惠券类型：">
        <el-select v-model="coupon.type">
          <el-option
              v-for="type in typeOptions"
              :key="type.value"
              :label="type.label"
              :value="type.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="优惠券名称：" prop="name">
        <el-input v-model="coupon.name" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="适用平台：">
        <el-select v-model="coupon.platform">
          <el-option
              v-for="item in platformOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数量：" prop="count">
        <el-input v-model.number="coupon.count" placeholder="只能输入正整数" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="面额：" prop="amount">
        <el-input v-model.number="coupon.amount" placeholder="面值只能是数值，限2位小数" class="input-width">
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="每人限领：">
        <el-input v-model="coupon.perLimit" placeholder="只能输入正整数" class="input-width">
          <template slot="append">张</template>
        </el-input>
      </el-form-item>
      <el-form-item label="使用门槛：" prop="minPoint">
        <el-input v-model.number="coupon.minPoint" placeholder="只能输入正整数" class="input-width">
          <template slot="prepend">满</template>
          <template slot="append">元可用</template>
        </el-input>
      </el-form-item>
      <el-form-item label="有效期：">
        <el-date-picker type="date" placeholder="选择日期" v-model="coupon.startTime" style="width: 150px"></el-date-picker>
        <span style="margin-left: 20px;margin-right: 20px">至</span>
        <el-date-picker type="date" placeholder="选择日期" v-model="coupon.endTime" style="width: 150px"></el-date-picker>
      </el-form-item>
      <el-form-item label="可使用商品：">
        <el-radio-group v-model="coupon.useType">
          <el-radio-button :label="0">全场通用</el-radio-button>
          <el-radio-button :label="1">指定分类</el-radio-button>
          <el-radio-button :label="2">指定商品</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="coupon.useType===1">
        <el-cascader
            clearable
            placeholder="请选择分类名称"
            :props="{value: 'id', label: 'name'}"
            v-model="selectProductCate"
            :options="productCateOptions">
        </el-cascader>
        <el-button class="ml10" @click="handleAddProductCategoryRelation">添加</el-button>
        <el-table ref="productCateRelationTable"
                  :data="coupon.couponProductCategoryRelationList"
                  style="width: 100%;margin-top: 20px"
                  border>
          <el-table-column label="分类名称" align="center">
            <template slot-scope="scope">
              {{ productCateName(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button size="mini"
                         type="text"
                         @click="handleDeleteProductCateRelation(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item v-show="coupon.useType===2">
        <el-select
            v-model="selectProduct"
            filterable
            remote
            reserve-keyword
            placeholder="商品名称"
            :remote-method="searchProductMethod"
            :loading="selectProductLoading">
          <el-option
              v-for="item in selectProductOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            <span style="float: left">{{ item.name }}</span>
          </el-option>
        </el-select>
        <el-button class="ml10" @click="handleAddProductRelation">添加</el-button>
        <el-table ref="productRelationTable"
                  :data="coupon.couponProductRelationList"
                  style="width: 100%;margin-top: 20px"
                  border>
          <el-table-column label="商品名称" align="center">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button size="mini"
                         type="text"
                         @click="handleDeleteProductRelation(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="备注：">
        <el-input
            class="input-width"
            type="textarea"
            :rows="5"
            placeholder="请输入内容"
            v-model="coupon.note">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('couponFrom')">提交</el-button>
        <el-button v-if="!isEdit" @click="resetQuery('couponFrom')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { addCoupon, getCoupon, updateCoupon } from '@/api/sms/coupon';
import { listProduct, getProduct } from '@/api/pms/product';
import { listProductCategory } from '@/api/pms/productCategory';
import { treeFind, treeFindPath } from "@/utils";

const defaultCoupon = {
  type: 0,
  name: null,
  platform: 0,
  amount: null,
  perLimit: 1,
  minPoint: null,
  startTime: null,
  endTime: null,
  useType: 0,
  note: null,
  publishCount: null,
  couponProductRelationList: [],
  couponProductCategoryRelationList: []
};
const defaultTypeOptions = [
  {
    label: '全场赠券',
    value: 0
  },
  {
    label: '会员赠券',
    value: 1
  },
  {
    label: '购物赠券',
    value: 2
  },
  {
    label: '注册赠券',
    value: 3
  }
];
const defaultPlatformOptions = [
  {
    label: '全平台',
    value: 0
  },
  {
    label: '移动平台',
    value: 1
  },
  {
    label: 'PC平台',
    value: 2
  }
];
export default {
  name: 'CouponDetail',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    productCateName() {
      return function (row) {
        let productCateName = '';
        const path = treeFindPath(this.productCateOptions, item => item.id == row.id);
        for (const id of path) {
          const name = treeFind(this.productCateOptions, item => item.id === id).name;
          productCateName = productCateName ? productCateName + '>' + name : productCateName + name;
        }
        return productCateName;
      };
    }
  },
  data() {
    return {
      coupon: Object.assign({}, defaultCoupon),
      typeOptions: Object.assign({}, defaultTypeOptions),
      platformOptions: Object.assign({}, defaultPlatformOptions),
      rules: {
        name: [
          { required: true, message: '请输入优惠券名称', trigger: 'blur' },
          { min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur' }
        ],
        publishCount: [
          { type: 'number', required: true, message: '只能输入正整数', trigger: 'blur' }
        ],
        amount: [
          { type: 'number', required: true, message: '面值只能是数值，0.01-10000，限2位小数', trigger: 'blur' }
        ],
        minPoint: [
          { type: 'number', required: true, message: '只能输入正整数', trigger: 'blur' }
        ],
        count: [
          { type: 'number', required: true, message: '只能输入正整数', trigger: 'blur' }
        ]
      },
      selectProduct: null,
      selectProductLoading: false,
      selectProductOptions: [],
      selectProductCate: [],
      productCateOptions: []
    }
  },
  created() {
    this.getProductCateList().then(() => {
      if (this.isEdit) {
        getCoupon(this.$route.query.id).then(response => {
          this.coupon = response.data.smsCoupon;
          this.coupon.couponProductRelationList = [];
          this.coupon.couponProductCategoryRelationList = [];
          if (this.coupon.useType === 1) {
            this.coupon.couponProductCategoryRelationList = response.data.couponProductCategoryRelationList.map(cItem => {
              return treeFind(this.productCateOptions, item => item.id === cItem.productCategoryId);
            });
          } else if (this.coupon.useType === 2) {
            response.data.couponProductRelationList.forEach(pItem => {
              getProduct(pItem.productId, false).then(response => {
                this.coupon.couponProductRelationList.push(response.data.product);
              });
            });
          }
        });
      }
    });
  },
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let couponProductCategoryRelationList = null;
            let couponProductRelationList = null;
            if (this.coupon.useType === 1) {
              couponProductCategoryRelationList = this.coupon.couponProductCategoryRelationList.map(item => {
                return {
                  productCategoryId: item.id,
                  productCategoryName: item.name
                };
              });
            } else if (this.coupon.useType === 2) {
              couponProductRelationList = this.coupon.couponProductRelationList.map(item => {
                return {
                  productId: item.id,
                  productName: item.name
                };
              });
            }
            if (this.isEdit) {
              this.coupon.id = this.$route.query.id;
              updateCoupon({
                smsCoupon: this.coupon,
                couponProductCategoryRelationList: couponProductCategoryRelationList,
                couponProductRelationList: couponProductRelationList
              }).then(response => {
                this.$refs[formName].resetFields();
                this.msgSuccess('修改成功');
                this.$router.push({ path: '/sms/coupon' }).then(() => {
                  Object.assign(this.$data, this.$options.data());
                });
              });
            } else {
              addCoupon({
                smsCoupon: this.coupon,
                couponProductCategoryRelationList: couponProductCategoryRelationList,
                couponProductRelationList: couponProductRelationList
              }).then(response => {
                this.$refs[formName].resetFields();
                this.msgSuccess('提交成功')
                this.$router.push({ path: '/sms/coupon' }).then(() => {
                  Object.assign(this.$data, this.$options.data());
                });
              });
            }
          });
        } else {
          this.msgError('验证失败');
          return false;
        }
      });
    },
    resetQuery(formName) {
      this.$refs[formName].resetFields();
      this.coupon = Object.assign({}, defaultCoupon);
    },
    searchProductMethod(query) {
      if (query !== '') {
        this.loading = true;
        listProduct({ name: query }).then(response => {
          this.loading = false;
          this.selectProductOptions = response.rows;
        });
      } else {
        this.selectProductOptions = [];
      }
    },
    handleAddProductRelation() {
      if (this.selectProduct === null) {
        this.$message({
          message: '请先选择商品',
          type: 'warning'
        });
        return
      }
      this.coupon.couponProductRelationList.push(this.getProductById(this.selectProduct));
      this.selectProduct = null;
    },
    handleDeleteProductRelation(index, row) {
      this.coupon.couponProductRelationList.splice(index, 1);
    },
    handleAddProductCategoryRelation() {
      if (this.selectProductCate === null || this.selectProductCate.length === 0) {
        this.$message({
          message: '请先选择商品分类',
          type: 'warning'
        });
        return
      }
      this.coupon.couponProductCategoryRelationList.push(this.getProductCateByIds(this.selectProductCate));
      this.selectProductCate = [];
    },
    handleDeleteProductCateRelation(index, row) {
      this.coupon.couponProductCategoryRelationList.splice(index, 1);
    },
    getProductById(id) {
      for (let i = 0; i < this.selectProductOptions.length; i++) {
        if (id === this.selectProductOptions[i].id) {
          return this.selectProductOptions[i];
        }
      }
      return null;
    },
    getProductCateList() {
      return new Promise(resolve => {
        listProductCategory().then(response => {
          this.productCateOptions = this.handleTree(response.rows);
          resolve();
        });
      });
    },
    getProductCateByIds(ids) {
      return treeFind(this.productCateOptions, item => item.id === ids[ids.length - 1]);
    }
  }
}
</script>
<style scoped>
.form-container {
  border: 1px solid #EBEEF5;
  width: 70%;
  margin-top: 20px;
  margin-bottom: 20px;
  margin-left: 150px;
}

.input-width {
  width: 60%;
}
</style>